﻿package net.wangit.jdbc.table;


import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import net.wangit.jdbc.DBImplementor;
import net.wangit.jdbc.database.Database;
import net.wangit.util.Checker;

/**
 * 表元数据
 * @author watson
 *
 */
public class TableMeta implements Serializable {
	private static final long serialVersionUID = 1L;
	private String domain;
	private String name;
	private String schema = null;
	private String logTableName;
	private boolean quoted = false;

	private List<Column> columns = new ArrayList<Column>();
	private PrimaryKey primaryKey = new PrimaryKey();
	private Column versionColumn;
	private String columnsString;

	protected TableMeta(String domain, String name) {
		this.domain = domain;
		this.name = name;
	}

	public String getQualifiedName(DBImplementor db) {
		Database database = db.getJDBCSettings().getDatabase();
		String quotedName = getQuotedName(database);
		String schemaName = (this.schema == null) ? db.getJDBCSettings()
				.getDefaultSchema() : this.schema;
		if (Checker.isEmpty(schemaName)) {
			return quotedName;
		}
		return schemaName + database.getSchemaSeparator() + quotedName;
	}

	public String getName() {
		return this.name;
	}

	private String getQuotedName(Database database) {
		return ((this.quoted) ? database.openQuote() + this.name
				+ database.closeQuote() : this.name);
	}

	public PrimaryKey getPrimaryKey() {
		return this.primaryKey;
	}

	protected void addPrimaryKeyColumn(Column column) {
		this.primaryKey.getColumns().add(column);
	}

	public String getSchema() {
		return this.schema;
	}

	protected void setSchema(String schema) {
		this.schema = schema;
	}

	public List<Column> getColumns() {
		return this.columns;
	}

	public boolean containsColumn(String columnName) {
		return (this.columnsString.indexOf(columnName + ",") >= 0);
	}

	public Column getColumn(String columnName) {
		for (int i = 0; i < this.columns.size(); ++i) {
			Column column = (Column) this.columns.get(i);
			if (column.getName().equals(columnName)) {
				return column;
			}
		}
		return null;
	}

	protected void addColumn(Column column) {
		this.columns.add(column);
	}

	public Column getVersionColumn() {
		return this.versionColumn;
	}

	protected void setVersionColumn(Column version) {
		this.versionColumn = version;
	}

	public String getLogTableName() {
		return this.logTableName;
	}

	protected void setLogTableName(String logTableName) {
		this.logTableName = logTableName;
	}

	protected void setColumnsString(String columnsString) {
		this.columnsString = columnsString;
	}

	public String getDomain() {
		return this.domain;
	}
}